<?php

namespace app\web\controller;

use app\model\Modules;
use think\Db;
use app\model\Users as UserModel;
use think\Validate;
use think\Session;

class Users extends Base
{
    private $all_module;

    public function __construct()
    {
        parent::__construct();
        $this->all_module = Modules::order('id', 'desc')->column('distinct module_name');
        global $_G, $_P;
        $op = !empty($_P['op']) ? $_P['op'] : 'display';
        if (!$_G['isSuperAdmin'] && ($op != 'myaccount' && $op != 'myaccount_save')) {
            return_msg('无操作权限');
        }
    }

    public function users()
    {
        global $_P, $_G;
        $do = 'users';
        $op = !empty($_P['op']) ? $_P['op'] : 'display';

        switch ($op) {
            case 'display':
                return $this->lists();
                break;
            case 'module_users':
                return $this->moduleUsers();
                break;
            case 'module_users_add':
                return $this->addUser();
                break;
            case 'module_users_save':
                return $this->save();
                break;
            case 'edit':
            case 'module_users_edit':
                return $this->edit($op);
                break;
            case 'save':
                return $this->save();
                break;
            case 'delete':
                return $this->del();
                break;
            case 'myaccount':
                $op = 'myaccount';
                return view('/users', [
                        '_G' => $_G,
                        '_P' => $_P,
                        'op' => $op]
                );
                break;
            case 'myaccount_save':
                return $this->myaccountSave();
                break;
            default:
                return $this->lists();
                break;
        }
    }

    public function lists()
    {
        global $_G, $_P;
        $op = 'display';
        $param = input('param.');
        $user_level = isset($param['user_level']) && $param['user_level'] ? $param['user_level'] : 5;
        $where = " user_level = {$user_level} ";
        if (isset($param['keyword']) && $param['keyword']) {
            $keyword = $param['keyword'];
            //字符串长度大于3
            if (is_numeric($keyword) && mb_strlen($keyword) >= 3) {
                $where .= " and username like '%{$keyword}'";
            } else {
                $where .= " and username like '%{$keyword}%'";
            }
        }


        $sort = isset($param['sort']) && $param['sort'] ? $param['sort'] : 'id';
        $pageSize = 20;
        $page = isset($param['page']) && $param['page'] ? $param['page'] : 1;
        $modules = new UserModel();
        $list = $modules
            ->field('id,username,realname,module_name,user_level,status,joindate,starttime,endtime')
            ->where($where)
            ->order("{$sort} desc")
            ->paginate($pageSize, false, ['page' => $page]);
        $pager = pagination($list->total(), $page, $pageSize);
        return view('/users',
            [
                '_G' => $_G,
                '_P' => $_P,
                'op' => $op,
                'list' => $list,
                'pageSize' => $pageSize,
                'keyword' => $keyword,
                'user_level' => $user_level,
                'page' => $page,
                'sort' => $sort,
                'pager' => $pager,
                'total' => $list->total(),
                'all_module' => $this->all_module
            ]);
    }

    public function moduleUsers()
    {
        global $_G, $_P;
        $op = 'module_users';
        $param = input('param.');
        $user_level = 5;
        $module = $_P['m'];
        $where = " user_level = {$user_level} and module_name = '{$module}' ";
        if (isset($param['keyword']) && $param['keyword']) {
            $keyword = $param['keyword'];
            //字符串长度大于3
            if (is_numeric($keyword) && mb_strlen($keyword) >= 3) {
                $where .= " and username like '%{$keyword}'";
            } else {
                $where .= " and username like '%{$keyword}%'";
            }
        }
        $pageSize = 20;
        $page = isset($param['page']) && $param['page'] ? $param['page'] : 1;
        $modules = new UserModel();
        $list = $modules
            ->field('id,username,module_name,user_level,status,joindate,starttime,endtime')
            ->where($where)
            ->order("id desc")
            ->paginate($pageSize, false, ['page' => $page]);

        return view('/module_users',
            [
                '_G' => $_G,
                '_P' => $_P,
                'list' => $list,
                'pageSize' => $pageSize,
                'keyword' => $keyword,
                'user_level' => $user_level,
                'page' => $page,
                'total' => $list->total(),
                'op' => $op,
                'module' => $module
            ]);
    }

    public function addUser()
    {
        global $_G, $_P;
        $op = 'module_users_add';
        $param = input('param.');
        $module_name = isset($param['module']) ? $param['module'] : '';
        if (!$module_name) {
            return_tips('模块名不能为空');
        }

        $username = UserModel::getPassword(2, 2) . substr($module_name, -5);
        do {  //用户名唯一跳出循环  不唯一继续生成
            $count = Db::table('yx_sys_users')->where('username', $username)->count();
            if ($count == 0) {
                break;
            }
            $username = UserModel::getPassword(2, 2) . substr($module_name, -5);
        } while (true);

        $password = UserModel::getPassword(1, 6);
        $salt = UserModel::random(8);
        $data = [
            'username' => $username,
            'password' => UserModel::userHash($password, $salt),
            'salt' => $salt,
            'module_name' => $module_name,
            'groupid' => 0,
            'user_level' => 5,
            'status' => 2,
            'joindate' => time(),
            'starttime' => time(),
            'endtime' => time() + 3600 * 24 * 45,
            'lastvisit' => 0,
        ];

        if (Db::table('yx_sys_users')->insert($data)) {
            $serverconfigs = Db::name('00serverconfig')->where('id', 1)->find();
            $serverconfig = !empty($serverconfigs['settings']) ? xunserializer($serverconfigs['settings']) : array();
            if ($serverconfig['companyname'] == '易宣软件') {
                $reginfo = '电脑版管理后台: ' . DOMAIN0 . chr(10) . '帐户: ' . $username . ' 密码: ' . $password . chr(10) . chr(10) . '🎉🎉🎉预祝大卖🎉🎉🎉' . chr(10) . chr(10) . '[拥抱]易宣微信营销专家[拥抱]' . chr(10) . '客服热线: 400 017 1899' . chr(10) .
                    '【须知:客户在线支付的报名费,腾讯将收取0.7%的手续费】';
            } else {
                $reginfo = '电脑版管理后台: ' . DOMAIN0 . chr(10) . '帐户: ' . $username . ' 密码: ' . $password . chr(10) . chr(10) . '【须知:客户在线支付的报名费,腾讯将收取0.7%的手续费】';
            }

            $res_data = [
                '_G' => $_G,
                '_P' => $_P,
                'op' => $op,
                'reginfo' => $reginfo,
            ];
            return view('/module_users', $res_data);
        } else {
            return_tips('添加失败');
        }
    }

    //获取用户信息
    public function edit($op)
    {
        global $_G, $_P;
        $id = $_P['id'];
        if (!$id) {
            return_tips('id不能为空', '', 'fail');
        }
        $info = Db::table('yx_sys_users')->where('id', $id)->find();
        if (!$info) {
            return_tips('用户不存在', '', 'fail');
        }
        if ($info['user_level'] < 3 && $_G['userlevel'] != 1) {
            return_tips('无权编辑', '', 'fail');
        }
        $info['endtime'] = date('Y-m-d', $info['endtime']);
        $view = $op == 'edit' ? 'users' : 'module_users';
        return view("/{$view}", [
            '_G' => $_G,
            '_P' => $_P,
            'info' => $info,
            'op' => $op,
            'all_module' => $this->all_module
        ]);
    }

    //用户编辑
    public function save()
    {
        global $_G, $_P;
        $post = input('post.');
        if ($post) {
            $id = $post['id'];
            if (!$id) {
                return_tips('id不能为空', '', 'fail');
            }
            $user = Db::table('yx_sys_users')->where('id', $id)->find();
            if (!$user) {
                return_tips('用户不存在', '', 'fail');
            }
            if ($user['user_level'] < 3 && $_G['userlevel'] != 1) {
                return_tips('无权编辑', '', 'fail');
            }

            if (isset($post['username']) && $post['username']) {
                $username = $post['username'];
                if ($username != $user['password']) {
                    //判断username断是否已存在
                    $has_appid = Db::table('yx_sys_users')->where('username', $username)->where('id', 'neq', $id)->count();
                    if ($has_appid > 0) {
                        return_tips('该用户名已存在');
                    }
                    $data['username'] = $post['username'];
                }
            }
            //如果密码不为空 为修改密码
            $password = $post['password'];
            $repassword = $post['repassword'];
            if (isset($post['password']) && $post['password']) {
                if (strlen($password) < 6) {
                    return_tips('密码不能小于6位');
                }
                if (strlen($password) > 16) {
                    return_tips('密码不能大于16位');
                }
                if ($password != $repassword) {
                    return_tips('两次密码不一致');
                }
                $password = UserModel::userHash($password, $user['salt']);
                if ($password != $user['password']) {
                    $data['password'] = $password;
                }
            }

            $endtype = isset($post['endtype']) ? $post['endtype'] : 0;
            if ($endtype == 1) {
                $data['endtime'] = 0;
            } elseif ($endtype == 2) {
                $endtime = strtotime($post['endtime']);
                if ($endtime != $user['endtime']) {
                    $data['endtime'] = $endtime;
                }
            }
            if ($data) {
                $res = Db::table('yx_sys_users')->where('id', $id)->update($data);
                if ($res !== false) {
                    return_tips('编辑成功');
                } else {
                    return_tips('编辑失败', '', 'fail');
                }
            } else {
                return_tips('没有修改', '', 'fail');
            }
        }
    }

    //删除用户
    public function del()
    {
        global $_G;
        $id = input('id');
        if (!$id) {
            return_tips('id不能为空');
        }
        $user = Db::table('yx_sys_users')->where('id', $id)->find();
        if (!$user) {
            return_tips('用户不存在');
        }
        if ($user['user_level'] < 3 && $_G['userlevel'] != 1) {
            return_tips('无权编辑', '', 'fail');
        }
        if ($user->user_level == 1) {
            return_tips('超级用户不可删除');
        }
        if (Db::table('yx_sys_users')->where('id', $id)->delete()) {
            return_tips('删除成功');
        } else {
            return_tips('删除失败');
        }
    }

    //保存我的账号
    public function myaccountSave()
    {
        $post = input('post.');
        if ($post) {
            $user = Session::get('userinfo');
            $username = $user['username'];
            $user = Db::table('yx_sys_users')->where('username', $username)->find();
            $password = $post['password'];
            $repassword = $post['repassword'];
            if (isset($post['password']) && $post['password']) {
                if (strlen($password) < 6) {
                    return_tips('密码不能小于6位');
                }
                if (strlen($password) > 16) {
                    return_tips('密码不能大于16位');
                }
                if ($password != $repassword) {
                    return_tips('两次密码不一致');
                }
                $password = UserModel::userHash($password, $user['salt']);
                if ($password != $user['password']) {
                    $data['password'] = $password;
                    $res = Db::table('yx_sys_users')->where('id', $user['id'])->update($data);
                    if ($res !== false) {
                        return_tips('保存成功');
                    } else {
                        return_tips('保存失败');
                    }
                } else {
                    return_tips('保存成功');
                }
            } else {
                return_tips('未做修改');
            }
        } else {
            return_tips('未提交数据');
        }
    }
}